package com.example.opcua_913.controller;

import com.example.opcua_913.model.OpcUaServer;
import com.example.opcua_913.test.OpcUaTest;
import com.example.opcua_913.utils.ResponseBodyMessage;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.atomic.AtomicInteger;

import static com.example.opcua_913.model.OpcUaServer.*;

/**
 * @author Man.Chen
 * @date 2023/9/14 17:53
 */
@RestController
public class OpcUaClientController {

    @Autowired
    public OpcUaServer opcUaServer;





    /**
     * 创建OPC UA客户端
     *
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/connect", method = RequestMethod.GET,produces = "applications/json;charset=UTF-8")

    public String  con(String endPointUrl) throws Exception {
//创建OPC UA客户端
        endPointUrl = "opc.tcp://127.0.0.1:49320";
        OpcUaClient client = createClient(endPointUrl);
        if (client == null){
            return "失败";
        }
        client.connect().get();
        return "成功";

    }

    /**
     * 读取节点数据
     *
     * @param
     * @throws Exception
     */
    @RequestMapping("/read")
    @ResponseBody
    public String read() throws Exception {
        String endPointUrl = "opc.tcp://127.0.0.1:49320,opc.tcp://127.0.0.1:49320,opc.tcp://127.0.0.1:49320";
        String[] split = endPointUrl.split(",");
        for (int i = 0; i < split.length; i++) {
            //创建OPC UA客户端
            OpcUaClient opcUaClient = createClient(split[i]);

            //开启连接
            opcUaClient.connect().get();

            //读
            readNode(opcUaClient);
            opcUaClient.disconnect().get();

        }
        return "运行完毕";
        }



    @RequestMapping("/write")
    @ResponseBody
    public String write() throws Exception {
        String endPointUrl = "opc.tcp://127.0.0.1:49320";
        //创建OPC UA客户端
        OpcUaClient opcUaClient = createClient(endPointUrl);
        //开启连接
        opcUaClient.connect().get();
        //写
        writeNodeValue(opcUaClient);
        return "成功";
    }


}
